import threading
import time
import urllib2
from urllib import urlopen
from BeautifulSoup import BeautifulSoup
import Image, ImageDraw, ImageFont
import UnityBackgroundChanger

# TODO cleanup!
# TODO add logging to a 'custom location'
# TODO allow debug printing (via a custom parameter)
# TODO make configurable to allow for random APOD pictures to be downloaded and set as the background periodically
class WebPoller(threading.Thread):

    timerWaitSec = 15.0 * 60 # set to 15 minutes by default (really should be configurable)
    unityBackgroundChanger = UnityBackgroundChanger.UnityBackgroundChanger()
    background = ""
    # url_base = 'http://apod.nasa.gov/apod/image/'
    
    def run(self):
        self.TimerLoop()
        
    # TODO: Make this configurable through a file or some UI...
    def TimerLoop(self):
        self.UrlFetch()
        while(True):
            time.sleep(self.timerWaitSec)
            self.UrlFetch()
        
    def UrlFetch(self):
        # TODO: make this configurable
        dest = '/opt/apod/'
 
        # TODO: make this configurable?
        doc = urllib2.urlopen('http://antwrp.gsfc.nasa.gov/apod/astropix.html')
        #print "Page is downloaded"
        soup = BeautifulSoup(doc)
        img = soup.find("center").findAll("a")
        url = img[1]['href']
        #print ' From: http://antwrp.gsfc.nasa.gov/apod/'+url+' to '+ dest+makeFilename(url)
        self.background = dest + self.makeFilename(url)
        self.download('http://antwrp.gsfc.nasa.gov/apod/' + url, self.background)
        title = soup.find("b").string
        self.AddTitle(self.background,title)
        
        # okay change out background to the new images
        # TODO make this more robust and possibly add some cross platform support (may be difficult, since calling OS libraries
        self.unityBackgroundChanger.set_background(self.background)
        
    def download(self, url,filename):
        """ download the binary file at url """
        instream = urlopen(url)
        outfile = open(filename,'wb')
        for chunk in instream:
            outfile.write(chunk)
        instream.close()
        outfile.close()
 
    def makeFilename(self, url):
        """ Turns the url into a filename by replacing possibly annoying characters by _ """    
        for c in ['/', ':', '?', '#', '&','%']:
            url = url.replace(c,'_')
        return url
     
    def AddTitle(self, filename, title):
        try:
            x = 0
            y = 1
            im = Image.open(filename)
            imSize = im.size
            if (imSize[y] <= 900):
                fontSize = 12
            elif (imSize[y] > 900 and imSize[y] <= 1800):
                fontSize = 24
            else:
                fontSize = 36
            # I need to get rid of this hard coded nonsense!
            fontName = "/usr/share/fonts/truetype/msttcorefonts/Arial.ttf"
            font = ImageFont.truetype(fontName, fontSize)
            fontHeight = font.getsize(title)[y]
            fontHeight = fontHeight + 5    
            newImageSize = (imSize[x], imSize[y] + fontHeight)
            imageData = (10, -fontHeight, imSize[x], imSize[y] + fontHeight)
            im = im.transform(newImageSize, Image.EXTENT, imageData)
            draw = ImageDraw.Draw(im)    
            fontPosition = (5, 5 + imSize[y])
            fontColor = "rgb(255,255,0)"
            draw.text(fontPosition, title, fill=fontColor, font=font)
            del draw
            im.save(filename)
        finally:
            pass
        